package com.intel.factorytest.ChamberMode;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.SystemProperties;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.app.ActionBar;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.app.StatusBarManager;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.view.Window;


import com.intel.factorytest.R;
import com.intel.factorytest.util.LogUtils;
import com.intel.factorytest.util.Util;
import com.intel.factorytest.util.ShellUtilsPlus;



public class ChamberModeMainActivity extends Activity implements View.OnClickListener {
        
    public static int WAIT_BEFORE_REBOOT_MS = 200;
    public static final int START_FRONT_CAMERA_TEST_REQUEST_CODE = 1;
    public static final int START_FRONT_CAMERA_TEST_RESULT_CODE = 2;
    public static final String FRONT_CAMERA_RESULT = "front_camera_result";
    
    public static final int START_REAR_CAMERA_TEST_REQUEST_CODE = 3;
    public static final int START_REAR_CAMERA_TEST_RESULT_CODE = 4;
    public static final String REAR_CAMERA_RESULT = "rear_camera_result";

    public static final int START_GPS_TEST_REQUEST_CODE = 5;
    public static final int START_GPS_TEST_RESULT_CODE = 6;
    public static final String GPS_RESULT = "gps_result";

    public static final int START_VIBRATOR_TEST_REQUEST_CODE = 7;
    public static final int START_VIBRATOR_TEST_RESULT_CODE = 8;
    public static final String VIBRATOR_RESULT = "vibrate_result";

    public static final int START_LTE_BAND_TEST_REQUEST_CODE = 9;
    public static final int START_LTE_BAND_TEST_RESULT_CODE = 10;
    public static final String LTE_BAND_RESULT = "lte_band_result";

    public static final int START_WIFI_TEST_REQUEST_CODE = 11;
    public static final int START_WIFI_TEST_RESULT_CODE = 12;
    public static final String WIFI_RESULT = "wifi_result";

    public static final int START_BT_TEST_REQUEST_CODE = 13;
    public static final int START_BT_TEST_RESULT_CODE = 14;
    public static final String BT_RESULT = "bt_result";

    public static final int START_SPEAKER_TEST_REQUEST_CODE = 15;
    public static final int START_SPEAKER_TEST_RESULT_CODE = 16;
    public static final String SPEAKER_RESULT = "speaker_result";

    public static final int START_EARPIEC_TEST_REQUEST_CODE = 17;
    public static final int START_EARPIEC_TEST_RESULT_CODE = 18;
    public static final String EARPIEC_RESULT = "earpiec_result";
    
    private final String CHAMBER_RUN_PROP = "persist.sys.chamber_run";
    private TextView mStatusiew;
    private TextView mShowText;
    private Button mStartButton;
    private Button mStopButton;    
    private LinearLayout mButtonView;
    Context mContext;
    private PackageInfo mPackageInfo;
    ActionBar  actionBar;
    StatusBarManager mStatusBarManager;
//SpeakerTest mSpeakerTest;
    //EarpiecTest mEarpiecTest;
    private boolean isSpeakerWorking = true;
    private boolean isEarpiecWorking = true;
    //ShellUtils.CmdResult mCmdResult;    
    private boolean isShowButton = true;
    ShellUtilsPlus.CommandResult mCmdResult;
    private String cmdSuccessMsg;
    private String cmdErrorMsg;
    private static final int MSG_TEST_SPEAKER = 1;
    private static final int MSG_TEST_EARPIEC = 2;
    private static final int MSG_TEST_FRONT_CAMERA = 3;
    private static final int MSG_TEST_REAR_CAMERA = 4;
    private static final int MSG_TEST_VIBRATOR = 5;
    private static final int MSG_TEST_WIFI_1 = 6;
    private static final int MSG_TEST_WIFI_2 = 7;
    private static final int MSG_TEST_BLUETOOTH = 8;
    private static final int MSG_TEST_GPS = 9;
    private static final int MSG_TEST_LTE_BAND = 10;
    private static final int MSG_UPDATE_SHOW_UI = 11;
    private static final int MSG_TEST_TEST_CODE = 12;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TEST_SPEAKER: {
                     removeMessages(MSG_TEST_SPEAKER);
                     Intent intent = new Intent(mContext, SpeakerTest.class);
                     startActivityForResult(intent, START_SPEAKER_TEST_REQUEST_CODE);
                     /*
                     removeMessages(MSG_TEST_SPEAKER);
                     Bundle b = msg.getData();
                     String s = b.getString("speaker_on_off");
                     LogUtils.logi( "speaker test get msg.getData String s = " + s);
                     if (s.equals("on")){
                         LogUtils.logi( "speaker test start");
                         isSpeakerWorking = true;
                         updateShowUI("Speaker Audio");
                         mSpeakerTest.startSpeaker(mContext);
                         sendDelayedMsg(MSG_TEST_SPEAKER,20000,"speaker_on_off","off");
                         sendDelayedMsg(MSG_UPDATE_SHOW_UI,5000,null,null); 
                     } else if(s.equals("off")){
                        LogUtils.logi( "speaker test stop");
                        isSpeakerWorking = true;
                        mSpeakerTest.stopSpeaker();
                        sendDelayedMsg(MSG_TEST_EARPIEC,5000,"earpice_on_off","on");
                        //sendDelayedMsg(MSG_TEST_SPEAKER,5000,"speaker_on_off","on");
                     } else if(s.equals("stop")){
                        LogUtils.logi( "speaker test stop and stop mode");
                        isSpeakerWorking = false;
                        mSpeakerTest.stopSpeaker();
                        removeMessages(MSG_TEST_SPEAKER);
                        removeMessages(MSG_TEST_EARPIEC);
                     }
                     */   
                    break;
                }
                case MSG_TEST_EARPIEC: {
                     removeMessages(MSG_TEST_EARPIEC);
                     Intent intent = new Intent(mContext, EarpiecTest.class);
                     startActivityForResult(intent, START_EARPIEC_TEST_REQUEST_CODE);
                    /*
                    removeMessages(MSG_TEST_EARPIEC);
                    Bundle b = msg.getData();
                    String s = b.getString("earpice_on_off");
                    LogUtils.logi( "earpice test get msg.getData String s = " + s);
                    if (s.equals("on")){
                        LogUtils.logi( "earpice test start");
                        isEarpiecWorking= true;
                        mEarpiecTest.startEarpiec(mContext);
                        updateShowUI("Earpiece Audio");                        
                        sendDelayedMsg(MSG_TEST_EARPIEC,20000,"earpice_on_off","off");
                        sendDelayedMsg(MSG_UPDATE_SHOW_UI,5000,null,null); 
                    } else if(s.equals("off")){
                       LogUtils.logi( "earpice test stop");
                       isEarpiecWorking = false;
                       mEarpiecTest.stopEarpiec();
                       sendDelayedMsg(MSG_TEST_FRONT_CAMERA,0,null,null);
                       //sendDelayedMsg(MSG_TEST_EARPIEC,5000,"earpice_on_off","on");
                    }else if(s.equals("stop")){
                        LogUtils.logi( "Earpiec test stop and stop mode");
                        isEarpiecWorking = false;
                        mEarpiecTest.stopEarpiec();
                        removeMessages(MSG_TEST_EARPIEC);
                        removeMessages(MSG_TEST_SPEAKER);
                    }
                       */
                    break;
                }
                case MSG_TEST_FRONT_CAMERA: {
                     removeMessages(MSG_TEST_FRONT_CAMERA);
                     Intent intent = new Intent(mContext, FrontCameraTest.class);
                     startActivityForResult(intent, START_FRONT_CAMERA_TEST_REQUEST_CODE);
                    break;
                }
                case MSG_TEST_REAR_CAMERA: {
                     removeMessages(MSG_TEST_REAR_CAMERA);
                     Intent intent = new Intent(mContext, RearCameraTest.class);
                     startActivityForResult(intent, START_REAR_CAMERA_TEST_REQUEST_CODE);
                    break;
                }
                case MSG_TEST_GPS: {
                     removeMessages(MSG_TEST_GPS);
                     Intent intent = new Intent(mContext, GnssTest.class);
                     startActivityForResult(intent, START_GPS_TEST_REQUEST_CODE);
                    break;
                }
                case MSG_TEST_VIBRATOR: {
                     removeMessages(MSG_TEST_VIBRATOR);
                     Intent intent = new Intent(mContext, VibrateTest.class);
                     startActivityForResult(intent, START_VIBRATOR_TEST_REQUEST_CODE);
                    break;
                }
                case MSG_TEST_WIFI_1: {
                     removeMessages(MSG_TEST_WIFI_1);
                     SystemProperties.set("persist.sys.chamber.diagcmd","null");
                     Intent intent = new Intent(mContext, WifiTest.class);
                     startActivityForResult(intent, START_WIFI_TEST_REQUEST_CODE);
                    break;
                }
                case MSG_TEST_BLUETOOTH: {
                     removeMessages(MSG_TEST_BLUETOOTH);
                     SystemProperties.set("persist.sys.chamber.bandtest","null");
                     SystemProperties.set("persist.sys.chamber.diagcmd","null");
                     Intent intent = new Intent(mContext, BluetoothTest.class);
                     startActivityForResult(intent, START_BT_TEST_REQUEST_CODE);
                    break;
                }
                case MSG_TEST_LTE_BAND: {
                     removeMessages(MSG_TEST_LTE_BAND);
                     SystemProperties.set("persist.sys.chamber.bandtest","null");
                     Intent intent = new Intent(mContext, LTEBandTest.class);
                     startActivityForResult(intent, START_LTE_BAND_TEST_REQUEST_CODE);
                    break;
                }
                case MSG_UPDATE_SHOW_UI: {
                     removeMessages(MSG_UPDATE_SHOW_UI);
                     updateShowUI("");
                    break;
                }
                /*
                case MSG_TEST_TEST_CODE: {
                     //This is test code                     
                     removeMessages(MSG_TEST_TEST_CODE);
                     mCmdResult = ShellUtilsPlus.execCommand("diag_tools -f /system/bin/diagcmd/bandtestin.txt",false);
                     //mCmdResult = ShellUtils.exec("diag_tools -f /system/bin/diag/bandtestin.txt");
                     cmdSuccessMsg = mCmdResult.successMsg;
                     cmdErrorMsg = mCmdResult.errorMsg;
                     LogUtils.logi( "Test get Success Msg = " + cmdSuccessMsg + ", Error Msg = " + cmdErrorMsg);
                    break;
                }
                */
                case MSG_TEST_TEST_CODE: {
                     removeMessages(MSG_TEST_TEST_CODE);
                     LogUtils.logi( "MSG_TEST_TEST_CODE" + MSG_TEST_TEST_CODE);
                    break;
                }
                
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = getApplicationContext();
        //Keep screen on.
        Util.wakeUpAndKeepScreenOn(this);
        //Util.setWindowBrightness(this,WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL);
        setContentView(R.layout.chamber_mode_activity_main);
        mStatusiew = (TextView) findViewById(R.id.status);
        mShowText = (TextView) findViewById(R.id.showtext);
        mStartButton = (Button) findViewById(R.id.start);
        mStopButton = (Button) findViewById(R.id.stop);
        mStartButton.setOnClickListener(this);
        mStopButton.setOnClickListener(this);
        if(isShowButton) {
            mButtonView = (LinearLayout)findViewById(R.id.bottom);
            mButtonView.setVisibility(View.GONE);
        }
        //for speaker test
        //mSpeakerTest = new SpeakerTest();
        //for Earpiec test
        //mEarpiecTest = new EarpiecTest();
        mStatusBarManager = (StatusBarManager)getSystemService(STATUS_BAR_SERVICE);
        /**Get version*/
        try {
            PackageManager pm = getPackageManager();
            mPackageInfo = pm.getPackageInfo(getPackageName(), PackageManager.GET_CONFIGURATIONS);
        } catch (PackageManager.NameNotFoundException e) {
            LogUtils.loge("get version failed");
        }
    }
    
    public void HideBottomMenu(){
        LogUtils.logi( "HideBottomMenu");
        mStatusBarManager.disable(StatusBarManager.DISABLE_MASK);
        actionBar = getActionBar();
        if(actionBar != null) {
               actionBar.hide();
        }
        View decorView = this.getWindow().getDecorView();        
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        actionBar = getActionBar();
                        if(actionBar != null) {
                            actionBar.hide();
                        }
                        View decorView = getWindow().getDecorView();
                        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_IMMERSIVE
                                | View.SYSTEM_UI_FLAG_FULLSCREEN;
                        decorView.setSystemUiVisibility(uiOptions);
                    }
            });
    }
    

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) || (keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)){
           return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                startTest();
                break;
            case R.id.stop:
                stopTest();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();        
        SystemProperties.set("sys.cit.key.test","true");
        HideBottomMenu();        
        //sendDelayedMsg(MSG_TEST_TEST_CODE,10000,null,null);
        startTest();
    }

    @Override
    protected void onStop() {    
        LogUtils.logi( "onStop "); 
        // TODO Auto-generated method stub
        super.onStop();
    }
    
    @Override
    protected void onPause() {    
        LogUtils.logi( "onPause "); 
        SystemProperties.set("sys.cit.key.test","false");
        super.onPause();
    }

    @Override
    protected void onDestroy() {        
        LogUtils.logi( "onDestroy "); 
        mStatusBarManager.disable(StatusBarManager.DISABLE_NONE);
        //Util.setWindowBrightness(this,WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE);
        super.onDestroy();
    }

    @Override
    public void finish() {
        LogUtils.logi( "finish "); 
        super.finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.logi( "onActivityResult: requestCode :" + requestCode + " resultCode:" + resultCode);
        updateShowUI("Waiting next test");
        if(requestCode == START_FRONT_CAMERA_TEST_REQUEST_CODE && resultCode == START_FRONT_CAMERA_TEST_RESULT_CODE) {
           String result_front = data.getStringExtra(FRONT_CAMERA_RESULT);
           LogUtils.logi( "onActivityResult: result_front :" + result_front);
           sendDelayedMsg(MSG_TEST_REAR_CAMERA,5000,null,null);
        }else if(requestCode == START_REAR_CAMERA_TEST_REQUEST_CODE && resultCode == START_REAR_CAMERA_TEST_RESULT_CODE) {
            String result_real = data.getStringExtra(REAR_CAMERA_RESULT);
            LogUtils.logi( "onActivityResult: result_real :" + result_real);            
            sendDelayedMsg(MSG_TEST_VIBRATOR,5000,null,null);
        }else if(requestCode == START_GPS_TEST_REQUEST_CODE && resultCode == START_GPS_TEST_RESULT_CODE) {
            String result_gps = data.getStringExtra(GPS_RESULT);
            LogUtils.logi( "onActivityResult: result_gps :" + result_gps);            
            sendDelayedMsg(MSG_TEST_LTE_BAND,5000,null,null);
        }else if(requestCode == START_VIBRATOR_TEST_REQUEST_CODE && resultCode == START_VIBRATOR_TEST_RESULT_CODE) {
            String result_vibrate = data.getStringExtra(VIBRATOR_RESULT);
            LogUtils.logi( "onActivityResult: result_vibrate :" + result_vibrate);            
            sendDelayedMsg(MSG_TEST_WIFI_1,5000,null,null);
        }else if(requestCode == START_LTE_BAND_TEST_REQUEST_CODE && resultCode == START_LTE_BAND_TEST_RESULT_CODE) {
            String result_lte_band = data.getStringExtra(LTE_BAND_RESULT);
            LogUtils.logi( "onActivityResult: result_lte_band :" + result_lte_band);
            reboot(mContext);
        }else if(requestCode == START_WIFI_TEST_REQUEST_CODE && resultCode == START_WIFI_TEST_RESULT_CODE) {
            String result_wifi = data.getStringExtra(WIFI_RESULT);
            LogUtils.logi( "onActivityResult: result_wifi :" + result_wifi);            
            sendDelayedMsg(MSG_TEST_BLUETOOTH,5000,null,null);
        }else if(requestCode == START_BT_TEST_REQUEST_CODE && resultCode == START_BT_TEST_RESULT_CODE) {
            String result_bt = data.getStringExtra(BT_RESULT);
            LogUtils.logi( "onActivityResult: result_bt :" + result_bt);
            sendDelayedMsg(MSG_TEST_GPS,5000,null,null);
        }else if(requestCode == START_SPEAKER_TEST_REQUEST_CODE && resultCode == START_SPEAKER_TEST_RESULT_CODE) {
            String result_speaker = data.getStringExtra(SPEAKER_RESULT);
            LogUtils.logi( "onActivityResult: result_speaker :" + result_speaker);            
            sendDelayedMsg(MSG_TEST_EARPIEC,5000,null,null);
        }else if(requestCode == START_EARPIEC_TEST_REQUEST_CODE && resultCode == START_EARPIEC_TEST_RESULT_CODE) {
            String result_earpiec = data.getStringExtra(EARPIEC_RESULT);
            LogUtils.logi( "onActivityResult: result_earpiec :" + result_earpiec);
            sendDelayedMsg(MSG_TEST_FRONT_CAMERA,5000,null,null);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    public void startTest() {
        LogUtils.logi( "startTest");
        //init Test
        //start speaker test
        //sendDelayedMsg(MSG_TEST_SPEAKER,0,"speaker_on_off","on");
        //start Earpiec test test code
        //sendDelayedMsg(MSG_TEST_EARPIEC,5000,"earpice_on_off","on");
        //start front camer test code
        //sendDelayedMsg(MSG_TEST_FRONT_CAMERA,0,null,null);
        //start GPS test code
        //sendDelayedMsg(MSG_TEST_GPS,0,null,null);
        //start Vibrator test code
        // test code
        //sendDelayedMsg(MSG_TEST_TEST_CODE,0,null,null);
        //start test code

        LogUtils.logi( "startTest p1 = " + SystemProperties.get(CHAMBER_RUN_PROP,"null"));
        if(!(SystemProperties.get(CHAMBER_RUN_PROP).equals("true"))) {
            //SystemProperties.set(CHAMBER_RUN_PROP,"true");
            LogUtils.logi( "startTest p2 = " + SystemProperties.get(CHAMBER_RUN_PROP,"null"));
            //sendDelayedMsg(MSG_TEST_BLUETOOTH,0,null,null);
            if(Util.isSpeakerTesting) {
                sendDelayedMsg(MSG_TEST_SPEAKER,0,null,null);
            } else if (Util.isEarpiecTesting) {
                sendDelayedMsg(MSG_TEST_EARPIEC,0,null,null);
            } else if (Util.isFrontCameraTesting) {
                sendDelayedMsg(MSG_TEST_FRONT_CAMERA,0,null,null);
            } else if (Util.isRearCameraTesting) {
                sendDelayedMsg(MSG_TEST_REAR_CAMERA,0,null,null);
            } else if (Util.isVibrateTesting) {
                sendDelayedMsg(MSG_TEST_VIBRATOR,0,null,null);
            } else if (Util.isWifiTesting) {
                sendDelayedMsg(MSG_TEST_WIFI_1,0,null,null);
            } else if (Util.isBluetoothTesting) {
                sendDelayedMsg(MSG_TEST_BLUETOOTH,0,null,null);
            } else if (Util.isGnssTesting) {
                sendDelayedMsg(MSG_TEST_GPS,0,null,null);
            } else if (Util.isLTEBandTesting) {
                sendDelayedMsg(MSG_TEST_LTE_BAND,0,null,null);
            } else {
                sendDelayedMsg(MSG_TEST_SPEAKER,0,null,null);
            }
        }
        
    }

    public void stopTest() {
        finish();
    }

    public void sendDelayedMsg(int msg, long delayMillis, String putString, String value){        
        LogUtils.logi( "sendDelayedMsg msg = " + msg + ",delaytime = " + delayMillis + ",putString = " + putString + ",value = " + value);
        if(!TextUtils.isEmpty(putString)&&!TextUtils.isEmpty(value)){
            Bundle b = new Bundle();
            b.putString(putString, value);
            Message m = Message.obtain(mHandler, msg);
            m.setData(b);
            mHandler.sendMessageDelayed(m, delayMillis);
        }else{
            Message m = Message.obtain(mHandler, msg);
            mHandler.sendMessageDelayed(m, delayMillis);
        }
    }
    
    public void updateShowUI(String text) {        
        LogUtils.logi( "updateShowUI text = " + text);
        mShowText.setText(text);
    }
    
    /**
     * Implement reboot function immediately.
     */
    private static void reboot(Context context) {
        Intent requestReboot = new Intent(
                Intent.ACTION_REBOOT);
        requestReboot.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
        requestReboot.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(requestReboot);
    }

    /**
     * Implement power off function immediately.
     */
    private static void powerOff(Context context) {
        Intent requestShutdown = new Intent(
                Intent.ACTION_REQUEST_SHUTDOWN);
        requestShutdown.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
        requestShutdown.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(requestShutdown);
    }

}
